package model;

import java.util.Date;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import util.Consts;

public class FitsZipFile {
	
    private static final int BUFFER = 2048;
	
	public String makeZipFile(ArrayList<String> filePaths, String zipPath) throws IOException{
			
		String zipFileName="FITS." + this.getTimestamp().toString().replaceAll(":", ".").replaceAll(" ", ".") + ".zip";
	    BufferedInputStream origin = null;
	    
		FileOutputStream dest = new FileOutputStream(zipPath + zipFileName);
		ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
		byte data[] = new byte[BUFFER];

		Iterator<String> itr = filePaths.iterator();
		while(itr.hasNext()){
			String filepath = (String) itr.next();
			File f = new File(filepath);
			String filename = f.getName();
			FileInputStream fi = new FileInputStream(filepath);
			origin = new BufferedInputStream(fi, BUFFER);
			ZipEntry entry = new ZipEntry(filename);
			out.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            origin.close();   
		}
		out.close();
		return zipFileName;
	}
	
	private Timestamp getTimestamp(){
		Date date = new Date();
		Timestamp timeStamp = new Timestamp(date.getTime());
		return timeStamp;
	}

}
